<template>
  <div class="system-settings">
    <el-tabs v-model="activeTab" class="settings-tabs">
      <!-- 基本设置 -->
      <el-tab-pane label="基本设置" name="basic">
        <el-form
          ref="basicFormRef"
          :model="basicForm"
          :rules="basicFormRules"
          label-width="120px"
          class="settings-form"
        >
          <el-form-item label="系统名称" prop="systemName">
            <el-input
              v-model="basicForm.systemName"
              placeholder="请输入系统名称"
            />
          </el-form-item>
          <el-form-item label="系统Logo" prop="logo">
            <el-upload
              class="logo-uploader"
              action="/api/upload"
              :show-file-list="false"
              :on-success="handleLogoSuccess"
              :before-upload="beforeLogoUpload"
            >
              <img
                v-if="basicForm.logo"
                :src="basicForm.logo"
                class="logo-image"
              />
              <el-icon v-else class="logo-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <div class="upload-tip">建议尺寸：200x200px，支持jpg、png格式</div>
          </el-form-item>
          <el-form-item label="联系电话" prop="contactPhone">
            <el-input
              v-model="basicForm.contactPhone"
              placeholder="请输入联系电话"
            />
          </el-form-item>
          <el-form-item label="联系邮箱" prop="contactEmail">
            <el-input
              v-model="basicForm.contactEmail"
              placeholder="请输入联系邮箱"
            />
          </el-form-item>
          <el-form-item label="系统公告" prop="announcement">
            <el-input
              type="textarea"
              v-model="basicForm.announcement"
              :rows="4"
              placeholder="请输入系统公告"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveBasicSettings"
              >保存设置</el-button
            >
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <!-- 安全设置 -->
      <el-tab-pane label="安全设置" name="security">
        <el-form
          ref="securityFormRef"
          :model="securityForm"
          :rules="securityFormRules"
          label-width="120px"
          class="settings-form"
        >
          <el-form-item label="密码策略" prop="passwordPolicy">
            <el-checkbox-group v-model="securityForm.passwordPolicy">
              <el-checkbox label="length">最少8位字符</el-checkbox>
              <el-checkbox label="uppercase">必须包含大写字母</el-checkbox>
              <el-checkbox label="lowercase">必须包含小写字母</el-checkbox>
              <el-checkbox label="number">必须包含数字</el-checkbox>
              <el-checkbox label="special">必须包含特殊字符</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="登录安全" prop="loginSecurity">
            <el-switch
              v-model="securityForm.twoFactorAuth"
              active-text="启用双因素认证"
            />
          </el-form-item>
          <el-form-item label="登录失败限制" prop="loginAttempts">
            <el-input-number
              v-model="securityForm.loginAttempts"
              :min="3"
              :max="10"
            />
            <span class="input-help">次失败后锁定账号</span>
          </el-form-item>
          <el-form-item label="会话超时" prop="sessionTimeout">
            <el-input-number
              v-model="securityForm.sessionTimeout"
              :min="30"
              :max="240"
            />
            <span class="input-help">分钟后自动退出</span>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveSecuritySettings"
              >保存设置</el-button
            >
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <!-- 通知设置 -->
      <el-tab-pane label="通知设置" name="notification">
        <el-form
          ref="notificationFormRef"
          :model="notificationForm"
          label-width="120px"
          class="settings-form"
        >
          <el-form-item label="邮件通知">
            <el-switch
              v-model="notificationForm.emailNotification"
              active-text="启用"
              inactive-text="禁用"
            />
          </el-form-item>
          <el-form-item label="短信通知">
            <el-switch
              v-model="notificationForm.smsNotification"
              active-text="启用"
              inactive-text="禁用"
            />
          </el-form-item>
          <el-form-item label="通知事件">
            <el-checkbox-group v-model="notificationForm.notifyEvents">
              <el-checkbox label="newOrder">新订单提醒</el-checkbox>
              <el-checkbox label="refund">退款申请提醒</el-checkbox>
              <el-checkbox label="merchantApply">商家入驻申请提醒</el-checkbox>
              <el-checkbox label="userReport">用户举报提醒</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item
            label="SMTP服务器"
            v-if="notificationForm.emailNotification"
          >
            <el-input
              v-model="notificationForm.smtpServer"
              placeholder="请输入SMTP服务器地址"
            />
          </el-form-item>
          <el-form-item
            label="SMTP端口"
            v-if="notificationForm.emailNotification"
          >
            <el-input
              v-model="notificationForm.smtpPort"
              placeholder="请输入SMTP端口"
            />
          </el-form-item>
          <el-form-item
            label="发件邮箱"
            v-if="notificationForm.emailNotification"
          >
            <el-input
              v-model="notificationForm.senderEmail"
              placeholder="请输入发件邮箱"
            />
          </el-form-item>
          <el-form-item
            label="短信API密钥"
            v-if="notificationForm.smsNotification"
          >
            <el-input
              v-model="notificationForm.smsApiKey"
              placeholder="请输入短信API密钥"
              show-password
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveNotificationSettings"
              >保存设置</el-button
            >
            <el-button @click="testNotification">测试通知</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <!-- 备份设置 -->
      <el-tab-pane label="备份设置" name="backup">
        <el-form
          ref="backupFormRef"
          :model="backupForm"
          label-width="120px"
          class="settings-form"
        >
          <el-form-item label="自动备份">
            <el-switch
              v-model="backupForm.autoBackup"
              active-text="启用"
              inactive-text="禁用"
            />
          </el-form-item>
          <el-form-item label="备份周期" v-if="backupForm.autoBackup">
            <el-select v-model="backupForm.backupCycle">
              <el-option label="每天" value="daily" />
              <el-option label="每周" value="weekly" />
              <el-option label="每月" value="monthly" />
            </el-select>
          </el-form-item>
          <el-form-item label="备份时间" v-if="backupForm.autoBackup">
            <el-time-picker
              v-model="backupForm.backupTime"
              format="HH:mm"
              placeholder="选择时间"
            />
          </el-form-item>
          <el-form-item label="保留备份数">
            <el-input-number
              v-model="backupForm.keepBackups"
              :min="1"
              :max="30"
            />
            <span class="input-help">个备份文件</span>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveBackupSettings"
              >保存设置</el-button
            >
            <el-button type="success" @click="startManualBackup"
              >立即备份</el-button
            >
          </el-form-item>
        </el-form>

        <!-- 备份记录 -->
        <div class="backup-history">
          <div class="section-title">备份记录</div>
          <el-table :data="backupHistory" border style="width: 100%">
            <el-table-column prop="fileName" label="文件名" min-width="200" />
            <el-table-column prop="size" label="大小" width="120" />
            <el-table-column prop="createTime" label="创建时间" width="180" />
            <el-table-column label="操作" width="200">
              <template #default="scope">
                <el-button-group>
                  <el-button
                    type="primary"
                    size="small"
                    @click="downloadBackup(scope.row)"
                  >
                    <i class="fas fa-download"></i> 下载
                  </el-button>
                  <el-button
                    type="danger"
                    size="small"
                    @click="deleteBackup(scope.row)"
                  >
                    <i class="fas fa-trash"></i> 删除
                  </el-button>
                </el-button-group>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";

const activeTab = ref("basic");

// 基本设置
const basicFormRef = ref(null);
const basicForm = reactive({
  systemName: "桂林文化旅游管理系统",
  logo: "",
  contactPhone: "0773-1234567",
  contactEmail: "support@example.com",
  announcement: "欢迎使用桂林文化旅游管理系统",
});

const basicFormRules = {
  systemName: [{ required: true, message: "请输入系统名称", trigger: "blur" }],
  contactPhone: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
  ],
  contactEmail: [
    { required: true, message: "请输入联系邮箱", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
  ],
};

// 安全设置
const securityFormRef = ref(null);
const securityForm = reactive({
  passwordPolicy: ["length", "number"],
  twoFactorAuth: false,
  loginAttempts: 5,
  sessionTimeout: 120,
});

const securityFormRules = {
  loginAttempts: [
    { required: true, message: "请设置登录失败限制次数", trigger: "blur" },
  ],
  sessionTimeout: [
    { required: true, message: "请设置会话超时时间", trigger: "blur" },
  ],
};

// 通知设置
const notificationFormRef = ref(null);
const notificationForm = reactive({
  emailNotification: true,
  smsNotification: false,
  notifyEvents: ["newOrder", "refund"],
  smtpServer: "smtp.example.com",
  smtpPort: "587",
  senderEmail: "noreply@example.com",
  smsApiKey: "",
});

// 备份设置
const backupFormRef = ref(null);
const backupForm = reactive({
  autoBackup: true,
  backupCycle: "daily",
  backupTime: new Date(2024, 2, 1, 2, 0),
  keepBackups: 7,
});

// 备份记录
const backupHistory = ref([
  {
    fileName: "backup_20240301_020000.zip",
    size: "256MB",
    createTime: "2024-03-01 02:00:00",
  },
  {
    fileName: "backup_20240229_020000.zip",
    size: "255MB",
    createTime: "2024-02-29 02:00:00",
  },
]);

// Logo上传
const handleLogoSuccess = (res, file) => {
  basicForm.logo = URL.createObjectURL(file.raw);
};

const beforeLogoUpload = (file) => {
  const isJPG = file.type === "image/jpeg";
  const isPNG = file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG && !isPNG) {
    ElMessage.error("上传头像图片只能是 JPG 或 PNG 格式!");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("上传头像图片大小不能超过 2MB!");
    return false;
  }
  return true;
};

// 保存设置
const saveBasicSettings = async () => {
  if (!basicFormRef.value) return;

  await basicFormRef.value.validate((valid, fields) => {
    if (valid) {
      // TODO: 调用保存API
      ElMessage.success("基本设置保存成功");
    }
  });
};

const saveSecuritySettings = async () => {
  if (!securityFormRef.value) return;

  await securityFormRef.value.validate((valid, fields) => {
    if (valid) {
      // TODO: 调用保存API
      ElMessage.success("安全设置保存成功");
    }
  });
};

const saveNotificationSettings = () => {
  // TODO: 调用保存API
  ElMessage.success("通知设置保存成功");
};

const saveBackupSettings = () => {
  // TODO: 调用保存API
  ElMessage.success("备份设置保存成功");
};

// 测试通知
const testNotification = () => {
  ElMessage.success("测试通知已发送");
};

// 备份操作
const startManualBackup = () => {
  ElMessage.success("备份任务已启动");
};

const downloadBackup = (backup) => {
  // TODO: 实现下载逻辑
  console.log("下载备份", backup);
};

const deleteBackup = (backup) => {
  // TODO: 实现删除逻辑
  console.log("删除备份", backup);
};
</script>

<style scoped>
.system-settings {
  padding: 20px;
}

.settings-tabs {
  margin-bottom: 20px;
}

.settings-form {
  max-width: 800px;
  margin: 20px auto;
}

.logo-uploader {
  width: 200px;
  height: 200px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.logo-uploader:hover {
  border-color: #409eff;
}

.logo-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 200px;
  height: 200px;
  line-height: 200px;
  text-align: center;
}

.logo-image {
  width: 200px;
  height: 200px;
  display: block;
}

.upload-tip {
  font-size: 12px;
  color: #666;
  margin-top: 5px;
}

.input-help {
  margin-left: 10px;
  color: #666;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin: 20px 0;
  padding-left: 10px;
  border-left: 4px solid #409eff;
}

.backup-history {
  margin-top: 30px;
}
</style>
